package com.myteam.fugaocrm.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.myteam.fugaocrm.contant.ENUM_BILLING_TYPE;
import com.myteam.fugaocrm.contant.ENUM_DETAIL_TYPE;
import com.myteam.fugaocrm.contant.ENUM_PROJECT_SCHEDULE;
import com.myteam.fugaocrm.contant.ENUM_PROJECT_STATUS;
import com.myteam.fugaocrm.contant.ProjectConstant;
import com.myteam.fugaocrm.modle.FgCode;
import com.myteam.fugaocrm.modle.FgCompany;
import com.myteam.fugaocrm.modle.FgContract;
import com.myteam.fugaocrm.modle.FgContractDetail;
import com.myteam.fugaocrm.modle.FgCustomer;
import com.myteam.fugaocrm.modle.FgCustomerCompany;
import com.myteam.fugaocrm.modle.FgPartnerCompany;
import com.myteam.fugaocrm.modle.FgPartnerCompanyDetail;
import com.myteam.fugaocrm.modle.FgPartnerContact;
import com.myteam.fugaocrm.modle.FgPartnerProduct;
import com.myteam.fugaocrm.modle.FgProject;
import com.myteam.fugaocrm.modle.FgProjectLog;
import com.myteam.fugaocrm.modle.FgStaff;
import com.myteam.fugaocrm.service.CompanyServiceImpl;
import com.myteam.fugaocrm.service.PartnerContactServiceImpl;
import com.myteam.fugaocrm.service.PartnerProductServiceImpl;
import com.myteam.fugaocrm.service.ProjectServiceImpl;
import com.myteam.fugaocrm.service.StaffServiceImpl;
import com.myteam.fugaocrm.sqldb.mapper.FgCodeMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgContractDetailMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgContractMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgCustomerCompanyMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgCustomerMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgPartnerCompanyDetailMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgPartnerCompanyMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgProjectLogMapper;
import com.myteam.fugaocrm.sqldb.mapper.FgProjectMapper;

@Controller
@RequestMapping(ProjectConstant.PROJECT_URL_PATH )
public class ProjectController extends BaseController {
	
	@Resource 
	protected FgProjectMapper fgProjectMapper;
	
	@Resource 
	protected FgPartnerCompanyDetailMapper fgPartnerCompanyDetailMapper;
	
	@Resource 
	protected FgProjectLogMapper fgProjectLogMapper;
	
	@Resource 
	protected FgCustomerCompanyMapper fgCustomerCompanyMapper;
	
	@Resource 
	protected FgPartnerCompanyMapper fgPartnerCompanyMapper;
	
	@Resource 
	protected FgContractMapper fgContractMapper;
	
	@Resource 
	protected FgContractDetailMapper fgContractDetailMapper;
	
	@Resource 
	protected FgCustomerMapper fgCustomerMapper;
	
	@Resource 
	protected FgCodeMapper fgCodeMapper;
	
	@Resource
	protected ProjectServiceImpl projectServiceImpl;
	
	@Resource 
	protected CompanyServiceImpl companyServiceImpl;
	
	@Resource 
	protected StaffServiceImpl staffServiceImpl;
	
	@Resource 
	protected PartnerProductServiceImpl partnerProductServiceImpl;
	
	@Resource 
	protected PartnerContactServiceImpl partnerContactServiceImpl;
	
	
	/**
	 * 项目管理页
	 */
	@RequestMapping("projectPage")
	public ModelAndView projectPage(FgProject project) {
		logger.info("进入项目管理查询页面：projectPage");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		List<String> list = new ArrayList<String>();
    	list.add(ENUM_PROJECT_STATUS.BEFORE.getCode());
    	list.add(ENUM_PROJECT_STATUS.IMPLAMENT.getCode());
    	project.setProjectStatusList(list);
    	String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
    	
    	//如果使员工或者没有权限，都只能看当前认的负责项目
    	if("0".equals(permission)||"".equals(permission)){
    		project.setStaffId(Integer.valueOf(staffId));
    	}
    	logger.info("查询项目状态为："+ENUM_PROJECT_STATUS.BEFORE.getValue()+"和"+ENUM_PROJECT_STATUS.IMPLAMENT.getValue()+"的项目数据");
		List<FgProject> projectList = projectServiceImpl.findFgProjectList(project);
		int projectCount = 0;
		if(null != projectList){
			projectCount = projectList.size();
			
		}
    	//计算公告信息总页数
    	Integer count = Integer.valueOf(projectCount)/Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	Integer other = Integer.valueOf(projectCount)%Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	other = other==0?0:1;
		Map<String, Object> attrs = new HashMap<>();
		if("0".equals(permission)||"".equals(permission)){
    		attrs.put("permission","0");
    	}
		attrs.put("count", count+other);
		getParmMap(attrs);
		attrs.put("project", project);
		return new ModelAndView(ProjectConstant.PROJECT_PAGE, attrs);
	}
	
	/**
	 * 售前项目表单页
	 */
	@RequestMapping("projectBeforeFormPage")
	public ModelAndView projectBeforeFormPage() {
		logger.info("进入售前项目管理页面：projectBeforeFormPage");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String projectId = request.getParameter("projectId");
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		Map<String, Object> attrs = new HashMap<>();
    	if("0".equals(permission)||"".equals(permission)){
    		attrs.put("permission","0");
    	}
		if(StringUtils.isBlank(projectId)){
			attrs.put("error","没有找到相应的项目信息");
			return new ModelAndView(ProjectConstant.PROJECT_PAGE, attrs);
		}
		
		FgProject project = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
		if(Integer.parseInt(staffId)!=project.getStaffId()
				&&("0".equals(permission) || "".equals(permission))){
			attrs.put("error","您没有权限查看此项目");
			return new ModelAndView(ProjectConstant.PROJECT_PAGE, attrs);
		}
		
		getParmMap(attrs);
		selectByProjectId(Integer.parseInt(projectId), attrs);
		
		return new ModelAndView(ProjectConstant.PROJECT_BEFORE_FORM, attrs);
	}
	
	/**
	 * 执行项目表单页
	 */
	@RequestMapping("projectImplementFormPage")
	public ModelAndView projectImplementFormPage() {
		logger.info("进入售前项目管理页面：projectImplementFormPage");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String projectId = request.getParameter("projectId");
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		Map<String, Object> attrs = new HashMap<>();
		if(StringUtils.isBlank(projectId)){
			attrs.put("error","没有找到相映的项目信息");
			return new ModelAndView(ProjectConstant.PROJECT_PAGE, attrs);
		}else{
			FgProject project = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
			if(Integer.parseInt(staffId)!=project.getStaffId()
					&&("0".equals(permission) || "".equals(permission))){
				attrs.put("error","您没有权限查看此项目");
				return new ModelAndView(ProjectConstant.PROJECT_PAGE, attrs);
			}
			getParmMap(attrs);
			selectByProjectId(Integer.parseInt(projectId), attrs);
		}
		return new ModelAndView(ProjectConstant.PROJECT_IMPLEMENT_FORM, attrs);
	}
	
	/**
	 * 【管理员查询售中】表单页
	 */
	@RequestMapping("projectImplementFormPageAdmin")
	public ModelAndView projectImplementFormPageAdmin() {
		logger.info("进入售前项目管理页面：projectImplementFormPageAdmin");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String projectId = request.getParameter("projectId");
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		Map<String, Object> attrs = new HashMap<>();
		if(StringUtils.isBlank(projectId)){
			attrs.put("error","没有找到相映的项目信息");
			return new ModelAndView(ProjectConstant.PROJECT_PAGE, attrs);
		}else{
			FgProject project = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
			if(Integer.parseInt(staffId)!=project.getStaffId()
					&&("0".equals(permission) || "".equals(permission))){
				attrs.put("error","您没有权限查看此项目");
				return new ModelAndView(ProjectConstant.PROJECT_PAGE, attrs);
			}
			getParmMap(attrs);
			selectByProjectId(Integer.parseInt(projectId), attrs);
		}
		return new ModelAndView(ProjectConstant.PROJECT_IMPLEMENT_FORM_ADMIN, attrs);
	}
	
	/**
	 * 创建项目机会表单页
	 */
	@RequestMapping("projectAddFormPage")
	public ModelAndView projectAddFormPage() {
		logger.info("进入创建项目机会表单页面：projectAddFormPage");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		Map<String, Object> attrs = new HashMap<>();
		if("0".equals(permission)||"".equals(permission)){
			attrs.put("permission","0");
		}
		attrs.put("staffId", staffId);
		getParmMap(attrs);
		return new ModelAndView(ProjectConstant.ADD_PROJECT_PAGE, attrs);
	}
	
	/**
	 * 根据客户公司选取对应的客户联系人
	 */
	@RequestMapping("project/getCompanyList")
	@ResponseBody
	public List<Map<String, Object>> getCompanyList(Integer companyId) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		//根据客户公司ID查出公司负责人 TODO
		List<FgCustomer> customerList = fgCustomerMapper.allByCustomerCompanyId(companyId);
		if(customerList == null || customerList.size() == 0) {
			return list;
		}
		
		Map<String, Object> map = null;
		for(int i=0; i<customerList.size(); i++) {
			map = new HashMap<String, Object>();
			map.put("id", customerList.get(i).getCustomerId());
			map.put("name", customerList.get(i).getCustomerName());
			list.add(map);
		}
		
		return list;
	}
	
	/**
	 * 查询【管理员项目管理】列表单页
	 */
	@RequestMapping("projectQueryPageAdmin")
	public ModelAndView projectQueryPageAdmin(FgProject project) {
		logger.info("进入查询项目列表单页：projectQueryPage");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		//如果使员工或者没有权限，都只能看当前认的负责项目
    	if("0".equals(permission)||"".equals(permission)){
    		project.setStaffId(Integer.valueOf(staffId));
    	}
		
		List<String> list = new ArrayList<String>();
    	list.add(ENUM_PROJECT_STATUS.BEFORE.getCode());
    	list.add(ENUM_PROJECT_STATUS.IMPLAMENT.getCode());
    	list.add(ENUM_PROJECT_STATUS.REVOKE.getCode());
    	list.add(ENUM_PROJECT_STATUS.FINISH.getCode());
    	project.setProjectStatusList(list);
		List<FgProject> projectList = projectServiceImpl.findFgProjectList(project);
		int projectCount = 0;
		if(null != projectList){
			projectCount = projectList.size();
		}
    	//计算公告信息总页数
    	Integer count = Integer.valueOf(projectCount)/Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	Integer other = Integer.valueOf(projectCount)%Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	other = other==0?0:1;
		Map<String, Object> attrs = new HashMap<>();
		if("0".equals(permission)||"".equals(permission)){
    		attrs.put("permission","0");
    	}
		attrs.put("count", count+other);
		getParmMap(attrs);
		attrs.put("project", project);
		return new ModelAndView(ProjectConstant.PROJECT_QUERY_ADMIN, attrs);
	}
		
	/**
	 * 查询项目列表单页
	 */
	@RequestMapping("projectQueryPage")
	public ModelAndView projectQueryPage(FgProject project) {
		logger.info("进入查询项目列表单页：projectQueryPage");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		//如果使员工或者没有权限，都只能看当前认的负责项目
    	if("0".equals(permission)||"".equals(permission)){
    		project.setStaffId(Integer.valueOf(staffId));
    	}
		
		List<String> list = new ArrayList<String>();
    	list.add(ENUM_PROJECT_STATUS.BEFORE.getCode());
    	list.add(ENUM_PROJECT_STATUS.IMPLAMENT.getCode());
    	list.add(ENUM_PROJECT_STATUS.REVOKE.getCode());
    	list.add(ENUM_PROJECT_STATUS.FINISH.getCode());
    	project.setProjectStatusList(list);
		List<FgProject> projectList = projectServiceImpl.findFgProjectList(project);
		int projectCount = 0;
		if(null != projectList){
			projectCount = projectList.size();
		}
    	//计算公告信息总页数
    	Integer count = Integer.valueOf(projectCount)/Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	Integer other = Integer.valueOf(projectCount)%Integer.valueOf(ProjectConstant.EVERY_PAGE_COUNT);
    	other = other==0?0:1;
		Map<String, Object> attrs = new HashMap<>();
		if("0".equals(permission)||"".equals(permission)){
    		attrs.put("permission","0");
    	}
		attrs.put("count", count+other);
		getParmMap(attrs);
//		attrs.put("projectList", projectList);
		attrs.put("project", project);
		return new ModelAndView(ProjectConstant.PROJECT_QUERY, attrs);
	}
	
	/**
	 * 查询项目表单页
	 */
	@RequestMapping("projectQueryFormPage")
	public ModelAndView projectQueryFormPage() {
		logger.info("进入查询项目表单页面：projectQueryFormPage");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String projectId = request.getParameter("projectId");
		String permission = "";
    	if(null != request.getSession().getAttribute("permission")){
    		permission = request.getSession().getAttribute("permission").toString();
    	}
		Map<String, Object> attrs = new HashMap<>();
    	if("0".equals(permission)||"".equals(permission)){
    		attrs.put("permission","0");
    	}
		getParmMap(attrs);
		selectByProjectId(Integer.parseInt(projectId), attrs);
		return new ModelAndView(ProjectConstant.PROJECT_QUERY_FORM, attrs);
	}
	
	/**
	 * 保存创建项目机会
	 */
	@RequestMapping("saveProject")
	public ModelAndView saveProject(FgProject project) throws Exception{
		logger.info("执行保存项目机会：saveProject");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String staffName = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffName")){
			staffName = request.getSession().getAttribute("staffName").toString();
		}
		String expectedDealDateString = request.getParameter("expectedDealDateString");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        if(StringUtils.isNotBlank(expectedDealDateString)){
        	Date date = sdf.parse(expectedDealDateString); 
        	project.setExpectedDealDate(date);
        }
        String staffId1 = request.getParameter("staffId1");
        if(null != staffId1 && !"".equals(staffId1)){
        	project.setStaffId(Integer.parseInt(staffId1));
        }
		project.setCreatedUser(staffName);
//		project.setModifiedUser(staffName);
		project.setCreatedDate(new Date());
//		project.setModifiedDate(new Date());
		project.setIsDelete(0);
		project.setProjectStatus(ENUM_PROJECT_STATUS.BEFORE.getCode());
		fgProjectMapper.saveProject(project);
//		String path = request.getContextPath();
//		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		return new ModelAndView("redirect:/project/projectPage");
	}
	
	/**
	 * 执行确认立项
	 */
	@RequestMapping("projectApproval")
	public ModelAndView projectApproval(String projectId,
			String logUpdateListJson, String logInsertListJson, 
	        String partnerUpdateListJson,String partnerInsertListJson ) throws Exception{
		logger.info("执行确认立项：projectApproval");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String staffName = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffName")){
			staffName = request.getSession().getAttribute("staffName").toString();
		}
		if(StringUtils.isBlank(projectId)){
			logger.error("项目id不能为空。");
		}
		FgProject project = new FgProject();
		project = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
		if(null == project){
			logger.error("没有找到对应的项目数据。");
		}
		//创建合同数据
		FgContract fgContract = new FgContract();
		fgContract.setProjectId(Integer.parseInt(projectId));
		fgContract.setCreatedUser(staffName);
		fgContract.setCreatedDate(new Date());
		fgContract.setIsDelete(0);
		fgContractMapper.insertOne(fgContract);
		
		ModelAndView view = updateBeforeProject(logUpdateListJson, logInsertListJson, partnerUpdateListJson, partnerInsertListJson);
		
		//更新项目状态
		FgProject updateProject = new FgProject();
		updateProject.setProjectId(Integer.parseInt(projectId));
		updateProject.setModifiedUser(staffName);
		updateProject.setModifiedDate(new Date());
		updateProject.setProjectStatus(ENUM_PROJECT_STATUS.IMPLAMENT.getCode());
		fgProjectMapper.updateProjectSelective(updateProject);
		
		return view;
	}
	
	/**
	 * 执行废除项目
	 */
	@RequestMapping("revokeProject")
	public ModelAndView revokeProject(String projectId) {
		logger.info("执行废除项目：revokeProject");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String staffName = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffName")){
			staffName = request.getSession().getAttribute("staffName").toString();
		}
		if(StringUtils.isBlank(projectId)){
			logger.error("项目id不能为空。");
		}
		FgProject project = new FgProject();
		project = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
		if(null == project){
			logger.error("没有找到对应的项目数据。");
		}
		
		FgProject tempFgProject = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
		if(ENUM_PROJECT_STATUS.BEFORE.getCode().equals(tempFgProject.getProjectStatus())) {
			FgProject updateProject = new FgProject();
			updateProject.setProjectId(Integer.parseInt(projectId));
			updateProject.setModifiedUser(staffName);
			updateProject.setModifiedDate(new Date());
			updateProject.setProjectStatus(ENUM_PROJECT_STATUS.REVOKE.getCode());
			fgProjectMapper.updateProjectSelective(updateProject);
		}
		
		return new ModelAndView("redirect:/project/projectPage");
	}
	
	/**
	 * 执行废除项目
	 */
	@RequestMapping("revokeProjectAdmin")
	public ModelAndView revokeProjectAdmin(String projectId) {
		logger.info("执行废除项目：revokeProjectAdmin");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String staffName = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffName")){
			staffName = request.getSession().getAttribute("staffName").toString();
		}
		if(StringUtils.isBlank(projectId)){
			logger.error("项目id不能为空。");
		}
		FgProject project = new FgProject();
		project = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
		if(null == project){
			logger.error("没有找到对应的项目数据。");
		}
		
		FgProject updateProject = new FgProject();
		updateProject.setProjectId(Integer.parseInt(projectId));
		updateProject.setModifiedUser(staffName);
		updateProject.setModifiedDate(new Date());
		updateProject.setProjectStatus(ENUM_PROJECT_STATUS.REVOKE.getCode());
		fgProjectMapper.updateProjectSelective(updateProject);
		
		return new ModelAndView("redirect:/project/projectQueryPageAdmin");
	}
	
	/**
	 * 项目完成（结项验收）
	 */
	@RequestMapping("projectFinish")
	public ModelAndView projectFinish(String projectId, 
			String contractUpdateListJson, String contractInsertListJson,
			String contractPaymentUpdateListJson, String contractPaymentInsertListJson,
	        String partnerUpdateListJson, String partnerDetailUpdateListJson) throws Exception{
		logger.info("执行项目完成（结项验收）：projectFinish");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String staffName = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffName")){
			staffName = request.getSession().getAttribute("staffName").toString();
		}
		//基本信息校验
		if(StringUtils.isBlank(projectId)){
			logger.error("项目id不能为空。");
		}
		FgProject project = new FgProject();
		project = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
		if(null == project){
			logger.error("没有找到对应的项目数据。");
		}
		
		//保存信息
		ModelAndView view =  updateImplProject(
				contractUpdateListJson, 
				contractInsertListJson,
				contractPaymentUpdateListJson,
				contractPaymentInsertListJson, 
				partnerUpdateListJson,
				partnerDetailUpdateListJson);
		
		//更新项目状态
		FgProject updateProject = new FgProject();
		updateProject.setProjectId(Integer.parseInt(projectId));
		updateProject.setModifiedUser(staffName);
		updateProject.setModifiedDate(new Date());
		updateProject.setProjectStatus(ENUM_PROJECT_STATUS.FINISH.getCode());
		fgProjectMapper.updateProjectSelective(updateProject);
		
		return view;
//		return new ModelAndView("redirect:/project/projectPage");
	}
	
	/**
	 * 更新售前项目数据
	 */
	@RequestMapping("updateBeforeProject")
	public ModelAndView updateBeforeProject(String logUpdateListJson, String logInsertListJson, 
	        String partnerUpdateListJson,String partnerInsertListJson ) throws Exception{
		
		logger.info("更新售前项目数据：updateBeforeProject");
		
		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}

        String offer = request.getParameter("offer");//报价
        String expectedDealDate = request.getParameter("expectedDealDate");//预计成交日期
        String projectSchedule = request.getParameter("projectSchedule");//项目进度
        String customerId = request.getParameter("customerId");//客户负责人
        String isRepair = request.getParameter("isRepair");//是否有运维
        String repairStartDate = request.getParameter("repairStartDate");//运维开始时间
        String repairEndDate = request.getParameter("repairEndDate");//运维结束时间
        String projectId = request.getParameter("projectId");
        String note = request.getParameter("note");//全局备注
        String staffName = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffName")){
			staffName = request.getSession().getAttribute("staffName").toString();
			
		}
		
		if(StringUtils.isNotBlank(logUpdateListJson)){
			List<FgProjectLog> logUpdateList = JSON.parseArray(logUpdateListJson, FgProjectLog.class);
			for(FgProjectLog log : logUpdateList){
				log.setProjectId(Integer.parseInt(projectId));
				if(ProjectConstant.YES.equals(log.getIsDone())){
					log.setDoneDate(new Date());
				}
				log.setModifiedDate(new Date());
				log.setModifiedUser(staffName);
				fgProjectLogMapper.updateOne(log);
			}
		}
		if(StringUtils.isNotBlank(logInsertListJson)){
			List<FgProjectLog> logInsertList = JSON.parseArray(logInsertListJson, FgProjectLog.class);
			for(FgProjectLog log : logInsertList){
				
				//无数据不存储
				if("".equals(log.getTodoSomething()) && log.getTodoDate() == null && "N".equals(log.getIsDone())) {
					continue;
				}
				
				log.setProjectId(Integer.parseInt(projectId));
				log.setIsDelete(0);
				if(ProjectConstant.YES.equals(log.getIsDone())){
					log.setDoneDate(new Date());
				}
				log.setCreatedDate(new Date());
				log.setCreatedUser(staffName);
				fgProjectLogMapper.insertProjectLog(log);
			}
		}
		if(StringUtils.isNotBlank(partnerInsertListJson)){
			List<FgPartnerCompanyDetail> partnerDetailList = fgPartnerCompanyDetailMapper.selectByProjectId(Integer.parseInt(projectId));
			for(FgPartnerCompanyDetail detail : partnerDetailList){
				fgPartnerCompanyDetailMapper.deleteOne(detail.getPartnerDetailId());
			}
			
			List<FgPartnerCompanyDetail> partnerInsertList = JSON.parseArray(partnerInsertListJson, FgPartnerCompanyDetail.class);

			for(FgPartnerCompanyDetail detail: partnerInsertList) {
				if(detail.getPartnerCompanyId() == null) {
					continue;
				}
				detail.setProjectId(Integer.parseInt(projectId));
				detail.setIsDelete(0);
				detail.setCreatedDate(new Date());
				detail.setCreatedUser(staffName);
				fgPartnerCompanyDetailMapper.insertPartnerCompanyDetail(detail);
			}
		}
        
        //储存项目信息
        FgProject fgProject1 = new FgProject();
        fgProject1.setProjectId(Integer.parseInt(projectId));
        fgProject1.setOffer(offer);
        if(StringUtils.isBlank(note)) {
        	note = "";
        }
        fgProject1.setNote(note);
        if(StringUtils.isNotBlank(projectSchedule)){
        	fgProject1.setProjectSchedule(projectSchedule);
        }
        if(StringUtils.isNotBlank(customerId)){
        	fgProject1.setCustomerId(Integer.parseInt(customerId));
        }
        if(StringUtils.isNotBlank(isRepair)){
        	fgProject1.setIsRepair(isRepair);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        if(StringUtils.isNotBlank(expectedDealDate)){
        	Date date = sdf.parse(expectedDealDate); 
        	fgProject1.setExpectedDealDate(date);
        }
        if(StringUtils.isNotBlank(repairStartDate)){
        	Date date = sdf.parse(repairStartDate); 
        	fgProject1.setRepairStartDate(date);
        }
        if(StringUtils.isNotBlank(repairEndDate)){
        	Date date = sdf.parse(repairEndDate); 
        	fgProject1.setRepairEndDate(date);
        }
        fgProject1.setModifiedUser(staffName);
		fgProject1.setModifiedDate(new Date());
		fgProjectMapper.updateProjectSelective(fgProject1);
		
        return new ModelAndView("redirect:/project/projectPage");
	}
	
	/**
	 * 更新执行项目数据
	 * @param logUpdateListJson
	 * @param logInsertListJson
	 * @param partnerUpdateListJson
	 * @param partnerInsertListJson
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("updateImplProject")
	public ModelAndView updateImplProject(
		String contractBillingUpdateListJson, 
		String contractBillingInsertListJson, 
		String contractPaymentUpdateListJson, 
		String contractPaymentInsertListJson, 
		String partnerUpdateListJson,
		String partnerDetailUpdateListJson) throws Exception{
			
			logger.info("更新执行项目数据：updateImplProject");

			String staffId = "";
			if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
				staffId = request.getSession().getAttribute("staffId").toString();
			}
			if("".equals(staffId)){
				logger.error("没有登录，请重新登录");
				return new ModelAndView("redirect:/login.jsp");
			}
			
	        String offer = request.getParameter("offer");//报价
	        String expectedDealDate = request.getParameter("expectedDealDate");//预计成交日期
	        String projectSchedule = request.getParameter("projectSchedule");//项目进度
	        String isRepair = request.getParameter("isRepair");//是否有运维
	        String repairStartDate = request.getParameter("repairStartDate");//运维开始时间
	        String repairEndDate = request.getParameter("repairEndDate");//运维结束时间
	        
	        String contractId = request.getParameter("contractId");//合同id
	        String contractCode = request.getParameter("contractCode");//合同编码
	        String isSign = request.getParameter("isSign");//是否签订
	        String isDelivery = request.getParameter("isDelivery");//是否交货
	        String signDate = request.getParameter("signDate");//
	        String deliveryDate = request.getParameter("deliveryDate");//
	        String note = request.getParameter("note");//全局备注
	        
	        String projectId = request.getParameter("projectId");
	        String staffName = "";
			if(null != request.getSession() && null != request.getSession().getAttribute("staffName")){
				staffName = request.getSession().getAttribute("staffName").toString();
			}
			
			if(StringUtils.isNotBlank(contractBillingUpdateListJson)){
				List<FgContractDetail> contractUpdateList = JSON.parseArray(contractBillingUpdateListJson, FgContractDetail.class);
				for(FgContractDetail cd : contractUpdateList){
					cd.setProjectId(Integer.parseInt(projectId));
					cd.setDetailType(ENUM_DETAIL_TYPE.BILL.getCode());
					cd.setModifiedDate(new Date());
					cd.setModifiedUser(staffName);
					if(cd.getBillingMoney() == null || "".equals(cd.getBillingMoney())) {
						cd.setBillingMoney("0");
					}
					if(cd.getPaymentMoney() == null || "".equals(cd.getPaymentMoney())) {
						cd.setPaymentMoney("0");
					}
					fgContractDetailMapper.updateOne(cd);
				}
			}
			if(StringUtils.isNotBlank(contractBillingInsertListJson)){
				List<FgContractDetail> contractInsertList = JSON.parseArray(contractBillingInsertListJson, FgContractDetail.class);
				for(FgContractDetail contract : contractInsertList){
					contract.setProjectId(Integer.parseInt(projectId));
					contract.setContractId(Integer.parseInt(contractId));
					contract.setDetailType(ENUM_DETAIL_TYPE.BILL.getCode());
					contract.setIsDelete(0);
					contract.setModifiedDate(new Date());
					contract.setModifiedUser(staffName);
					contract.setCreatedDate(new Date());
					contract.setCreatedUser(staffName);
					if(contract.getBillingMoney() == null || "".equals(contract.getBillingMoney())) {
						contract.setBillingMoney("0");
					}
					if(contract.getPaymentMoney() == null || "".equals(contract.getPaymentMoney())) {
						contract.setPaymentMoney("0");
					}
					fgContractDetailMapper.insertOne(contract);
				}
			}
			if(StringUtils.isNotBlank(contractPaymentUpdateListJson)){
				List<FgContractDetail> contractUpdateList = JSON.parseArray(contractPaymentUpdateListJson, FgContractDetail.class);
				for(FgContractDetail cd : contractUpdateList){
					cd.setProjectId(Integer.parseInt(projectId));
					cd.setDetailType(ENUM_DETAIL_TYPE.PAY.getCode());
					cd.setModifiedDate(new Date());
					cd.setModifiedUser(staffName);
					if(cd.getBillingMoney() == null || "".equals(cd.getBillingMoney())) {
						cd.setBillingMoney("0");
					}
					if(cd.getPaymentMoney() == null || "".equals(cd.getPaymentMoney())) {
						cd.setPaymentMoney("0");
					}
					fgContractDetailMapper.updateOne(cd);
				}
			}
			if(StringUtils.isNotBlank(contractPaymentInsertListJson)){
				List<FgContractDetail> contractInsertList = JSON.parseArray(contractPaymentInsertListJson, FgContractDetail.class);
				for(FgContractDetail contract : contractInsertList){
					contract.setProjectId(Integer.parseInt(projectId));
					contract.setContractId(Integer.parseInt(contractId));
					contract.setDetailType(ENUM_DETAIL_TYPE.PAY.getCode());
					contract.setIsDelete(0);
					contract.setModifiedDate(new Date());
					contract.setModifiedUser(staffName);
					contract.setCreatedDate(new Date());
					contract.setCreatedUser(staffName);
					if(contract.getBillingMoney() == null || "".equals(contract.getBillingMoney())) {
						contract.setBillingMoney("0");
					}
					if(contract.getPaymentMoney() == null || "".equals(contract.getPaymentMoney())) {
						contract.setPaymentMoney("0");
					}
					fgContractDetailMapper.insertOne(contract);
				}
			}
			//供应商数据
			if(StringUtils.isNotBlank(partnerUpdateListJson) && StringUtils.isNotBlank(partnerDetailUpdateListJson)) {
				List<FgPartnerCompanyDetail> partnerDetailList = fgPartnerCompanyDetailMapper.selectByProjectId(Integer.parseInt(projectId));
				for(FgPartnerCompanyDetail detail : partnerDetailList){
					fgPartnerCompanyDetailMapper.deleteOne(detail.getPartnerDetailId());
				}
				
				List<FgPartnerCompanyDetail> partnerInsertList = JSON.parseArray(partnerUpdateListJson, FgPartnerCompanyDetail.class);
				List<FgPartnerCompanyDetail> partnerDetailUpdateList = JSON.parseArray(partnerDetailUpdateListJson, FgPartnerCompanyDetail.class);
				
				for(int i=0; i<partnerInsertList.size(); i++) {
					FgPartnerCompanyDetail detail = partnerInsertList.get(i);
					FgPartnerCompanyDetail temp   = new FgPartnerCompanyDetail();
					if(i < partnerDetailUpdateList.size()) {
						temp = partnerDetailUpdateList.get(i);
					}
					
					if(detail.getPartnerCompanyId() == null) {
						continue;
					}
					
					detail.setIsShipment(temp.getIsShipment());
					detail.setShipmentDate(temp.getShipmentDate());
					detail.setIsBilling(temp.getBillingType());
					detail.setBillingType(temp.getBillingType());
					detail.setBillingDate(temp.getBillingDate());
					detail.setIsPayment(temp.getIsPayment());
					detail.setPaymentDate(temp.getPaymentDate());
					
					detail.setProjectId(Integer.parseInt(projectId));
					detail.setIsDelete(0);
					detail.setCreatedDate(new Date());
					detail.setCreatedUser(staffName);
					fgPartnerCompanyDetailMapper.insertPartnerCompanyDetail(detail);
				}
			}
	        
	        //校验项目是否存在
	        FgProject fgProject = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
	        //储存项目信息
	        FgProject fgProject1 = new FgProject();
	        fgProject1.setProjectId(Integer.parseInt(projectId));
	        fgProject1.setOffer(offer);
	        
	        if(StringUtils.isBlank(note)) {
	        	note = "";
	        }
	        fgProject1.setNote(note);
	        
	        if(StringUtils.isNotBlank(projectSchedule)){
	        	fgProject1.setProjectSchedule(projectSchedule);
	        }
	        if(StringUtils.isNotBlank(isRepair)){
	        	fgProject1.setIsRepair(isRepair);
	        }
	        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
	        if(StringUtils.isNotBlank(expectedDealDate)){
	        	Date date = sdf.parse(expectedDealDate); 
	        	fgProject1.setExpectedDealDate(date);
	        }
	        if(StringUtils.isNotBlank(repairStartDate)){
	        	Date date = sdf.parse(repairStartDate); 
	        	fgProject1.setRepairStartDate(date);
	        }else{
	        	fgProject1.setRepairStartDate(null);
	        }
	        if(StringUtils.isNotBlank(repairEndDate)){
	        	Date date = sdf.parse(repairEndDate); 
	        	fgProject1.setRepairEndDate(date);
	        }else{
	        	fgProject1.setRepairEndDate(null);
	        }
	        fgProject1.setModifiedUser(staffName);
			fgProject1.setModifiedDate(new Date());
			fgProjectMapper.updateProjectSelective(fgProject1);
			//保存合同
			FgContract fgContract = new FgContract();
			fgContract.setIsSign(isSign);
			if(ProjectConstant.YES.equals(isSign) && StringUtils.isBlank(contractCode)){
				contractCode = getContractCode(fgProject.getCompanyId());
			}
			fgContract.setContractCode(contractCode);//合同编码
			fgContract.setIsDelivery(isDelivery);
			if(StringUtils.isNotBlank(signDate)){
	        	Date date = sdf.parse(signDate); 
	        	fgContract.setSignDate(date);
	        }
			if(StringUtils.isNotBlank(deliveryDate)){
	        	Date date = sdf.parse(deliveryDate); 
	        	fgContract.setDeliveryDate(date);
	        }
			fgContract.setModifiedDate(new Date());
			fgContract.setModifiedUser(staffName);
			if(StringUtils.isNotBlank(contractId)){
				fgContract.setContractId(Integer.valueOf(contractId));
			}
			fgContractMapper.updateOne(fgContract);
	        return new ModelAndView("redirect:/project/projectPage");
		}
	/**
	 * 管理员修改项目子页面
	 * @param contractBillingUpdateListJson
	 * @param contractBillingInsertListJson
	 * @param contractPaymentUpdateListJson
	 * @param contractPaymentInsertListJson
	 * @param partnerUpdateListJson
	 * @param partnerDetailUpdateListJson
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("updateImplProjectAdmin")
	public ModelAndView updateImplProjectAdmin(
			String contractBillingUpdateListJson, 
			String contractBillingInsertListJson, 
			String contractPaymentUpdateListJson, 
			String contractPaymentInsertListJson, 
			String partnerUpdateListJson,
			String partnerDetailUpdateListJson) throws Exception{
		
		logger.info("更新执行项目数据：updateImplProject");

		String staffId = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffId")){
			staffId = request.getSession().getAttribute("staffId").toString();
		}
		if("".equals(staffId)){
			logger.error("没有登录，请重新登录");
			return new ModelAndView("redirect:/login.jsp");
		}
		
		String customerCompanyId = request.getParameter("customerCompany");//客户公司
		String customerId = request.getParameter("customer");//客户负责人
		String companyId = request.getParameter("company");//接单部门
		String staffId2 = request.getParameter("staff");//项目负责人
		
        String offer = request.getParameter("offer");//报价
        String expectedDealDate = request.getParameter("expectedDealDate");//预计成交日期
        String projectSchedule = request.getParameter("projectSchedule");//项目进度
        String isRepair = request.getParameter("isRepair");//是否有运维
        String repairStartDate = request.getParameter("repairStartDate");//运维开始时间
        String repairEndDate = request.getParameter("repairEndDate");//运维结束时间
        String note = request.getParameter("note");//全局备注
        
        String contractId = request.getParameter("contractId");//合同id
        String contractCode = request.getParameter("contractCode");//合同编码
        String isSign = request.getParameter("isSign");//是否签订
        String isDelivery = request.getParameter("isDelivery");//是否交货
        String signDate = request.getParameter("signDate");//
        String deliveryDate = request.getParameter("deliveryDate");//
        
        String projectId = request.getParameter("projectId");
        String staffName = "";
		if(null != request.getSession() && null != request.getSession().getAttribute("staffName")){
			staffName = request.getSession().getAttribute("staffName").toString();
		}
		
		if(StringUtils.isNotBlank(contractBillingUpdateListJson)){
			List<FgContractDetail> contractUpdateList = JSON.parseArray(contractBillingUpdateListJson, FgContractDetail.class);
			for(FgContractDetail cd : contractUpdateList){
				cd.setProjectId(Integer.parseInt(projectId));
				cd.setDetailType(ENUM_DETAIL_TYPE.BILL.getCode());
				cd.setModifiedDate(new Date());
				cd.setModifiedUser(staffName);
				fgContractDetailMapper.updateOne(cd);
			}
		}
		if(StringUtils.isNotBlank(contractBillingInsertListJson)){
			List<FgContractDetail> contractInsertList = JSON.parseArray(contractBillingInsertListJson, FgContractDetail.class);
			for(FgContractDetail contract : contractInsertList){
				contract.setProjectId(Integer.parseInt(projectId));
				contract.setContractId(Integer.parseInt(contractId));
				contract.setDetailType(ENUM_DETAIL_TYPE.BILL.getCode());
				contract.setIsDelete(0);
				contract.setModifiedDate(new Date());
				contract.setModifiedUser(staffName);
				contract.setCreatedDate(new Date());
				contract.setCreatedUser(staffName);
				fgContractDetailMapper.insertOne(contract);
			}
		}
		if(StringUtils.isNotBlank(contractPaymentUpdateListJson)){
			List<FgContractDetail> contractUpdateList = JSON.parseArray(contractPaymentUpdateListJson, FgContractDetail.class);
			for(FgContractDetail cd : contractUpdateList){
				cd.setProjectId(Integer.parseInt(projectId));
				cd.setDetailType(ENUM_DETAIL_TYPE.PAY.getCode());
				cd.setModifiedDate(new Date());
				cd.setModifiedUser(staffName);
				fgContractDetailMapper.updateOne(cd);
			}
		}
		if(StringUtils.isNotBlank(contractPaymentInsertListJson)){
			List<FgContractDetail> contractInsertList = JSON.parseArray(contractPaymentInsertListJson, FgContractDetail.class);
			for(FgContractDetail contract : contractInsertList){
				contract.setProjectId(Integer.parseInt(projectId));
				contract.setContractId(Integer.parseInt(contractId));
				contract.setDetailType(ENUM_DETAIL_TYPE.PAY.getCode());
				contract.setIsDelete(0);
				contract.setModifiedDate(new Date());
				contract.setModifiedUser(staffName);
				contract.setCreatedDate(new Date());
				contract.setCreatedUser(staffName);
				fgContractDetailMapper.insertOne(contract);
			}
		}
		//供应商数据
		if(StringUtils.isNotBlank(partnerUpdateListJson) && StringUtils.isNotBlank(partnerDetailUpdateListJson)) {
			List<FgPartnerCompanyDetail> partnerDetailList = fgPartnerCompanyDetailMapper.selectByProjectId(Integer.parseInt(projectId));
			for(FgPartnerCompanyDetail detail : partnerDetailList){
				fgPartnerCompanyDetailMapper.deleteOne(detail.getPartnerDetailId());
			}
			
			List<FgPartnerCompanyDetail> partnerInsertList = JSON.parseArray(partnerUpdateListJson, FgPartnerCompanyDetail.class);
			List<FgPartnerCompanyDetail> partnerDetailUpdateList = JSON.parseArray(partnerDetailUpdateListJson, FgPartnerCompanyDetail.class);
			
			for(int i=0; i<partnerInsertList.size(); i++) {
				FgPartnerCompanyDetail detail = partnerInsertList.get(i);
				FgPartnerCompanyDetail temp   = new FgPartnerCompanyDetail();
				if(i < partnerDetailUpdateList.size()) {
					temp = partnerDetailUpdateList.get(i);
				}
				
				if(detail.getPartnerCompanyId() == null) {
					continue;
				}
				
				detail.setIsShipment(temp.getIsShipment());
				detail.setShipmentDate(temp.getShipmentDate());
				detail.setIsBilling(temp.getBillingType());
				detail.setBillingType(temp.getBillingType());
				detail.setBillingDate(temp.getBillingDate());
				detail.setIsPayment(temp.getIsPayment());
				detail.setPaymentDate(temp.getPaymentDate());
				
				detail.setProjectId(Integer.parseInt(projectId));
				detail.setIsDelete(0);
				detail.setCreatedDate(new Date());
				detail.setCreatedUser(staffName);
				fgPartnerCompanyDetailMapper.insertPartnerCompanyDetail(detail);
			}
		}
        
        //校验项目是否存在
        FgProject fgProject = fgProjectMapper.selectByProjectId(Integer.parseInt(projectId));
        //储存项目信息
        FgProject fgProject1 = new FgProject();
        fgProject1.setProjectId(Integer.parseInt(projectId));
        fgProject1.setOffer(offer);

        if(StringUtils.isBlank(note)) {
        	note = "";
        }
        fgProject1.setNote(note);
        
        if(StringUtils.isNotBlank(staffId2)){
        	fgProject1.setStaffId(Integer.parseInt(staffId2));
        }
        if(StringUtils.isNotBlank(companyId)){
        	fgProject1.setCompanyId(Integer.parseInt(companyId));
        }
        if(StringUtils.isNotBlank(customerId)){
        	fgProject1.setCustomerId(Integer.parseInt(customerId));
        }
        if(StringUtils.isNotBlank(customerCompanyId)){
        	fgProject1.setCustomerCompanyId(Integer.parseInt(customerCompanyId));
        }
        if(StringUtils.isNotBlank(projectSchedule)){
        	fgProject1.setProjectSchedule(projectSchedule);
        }
        if(StringUtils.isNotBlank(isRepair)){
        	fgProject1.setIsRepair(isRepair);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
        if(StringUtils.isNotBlank(expectedDealDate)){
        	Date date = sdf.parse(expectedDealDate); 
        	fgProject1.setExpectedDealDate(date);
        }
        if(StringUtils.isNotBlank(repairStartDate)){
        	Date date = sdf.parse(repairStartDate); 
        	fgProject1.setRepairStartDate(date);
        }else{
        	fgProject1.setRepairStartDate(null);
        }
        if(StringUtils.isNotBlank(repairEndDate)){
        	Date date = sdf.parse(repairEndDate); 
        	fgProject1.setRepairEndDate(date);
        }else{
        	fgProject1.setRepairEndDate(null);
        }
        fgProject1.setModifiedUser(staffName);
		fgProject1.setModifiedDate(new Date());
		fgProjectMapper.updateProjectSelective(fgProject1);
		//保存合同
		FgContract fgContract = new FgContract();
		fgContract.setIsSign(isSign);
		if(ProjectConstant.YES.equals(isSign) && StringUtils.isBlank(contractCode)){
			contractCode = getContractCode(fgProject.getCompanyId());
		}
		fgContract.setContractCode(contractCode);//合同编码
		fgContract.setIsDelivery(isDelivery);
		if(StringUtils.isNotBlank(signDate)){
        	Date date = sdf.parse(signDate); 
        	fgContract.setSignDate(date);
        }
		if(StringUtils.isNotBlank(deliveryDate)){
        	Date date = sdf.parse(deliveryDate); 
        	fgContract.setDeliveryDate(date);
        }
		fgContract.setModifiedDate(new Date());
		fgContract.setModifiedUser(staffName);
		if(StringUtils.isNotBlank(contractId)){
			fgContract.setContractId(Integer.valueOf(contractId));
		}
		fgContractMapper.updateOne(fgContract);
        return new ModelAndView("redirect:/project/projectQueryPageAdmin");
	}
	
	/**
	 * 获取合同编码
	 * @param companyId
	 * @return
	 */
	private String getContractCode(Integer companyId){
		String contractCode = "";
		FgCode fgCode = new FgCode();
		fgCode.setCodeType("contractSeq");
		fgCode.setCode("seq");
		fgCode = fgCodeMapper.selectOne(fgCode);
		String value = fgCode.getCodeLable();
		int seq = Integer.valueOf(value) +1;
		String abcStr = seq+"";
		FgCode fgCode2 = new FgCode();
		fgCode2.setId(fgCode.getId());
		fgCode2.setCodeLable(abcStr);
		fgCodeMapper.updateOne(fgCode2);
		if(value.length()<2){
			abcStr = "00"+abcStr;
		}else if(value.length()<3){
			abcStr = "0"+abcStr;
		}
		Date date = new Date();
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
		String cmcode = "";
		List<FgCompany> companyList = companyServiceImpl.all();
		for(FgCompany fc : companyList){
			if(fc.getCompanyId() == companyId){
				cmcode = fc.getCompanyCode();
				break;
			}
		}
		contractCode = sdf1.format(date)+cmcode+abcStr;
		return contractCode;
	}

	/**
	 * 公用枚举
	 * @param attrs
	 */
	private void getParmMap(Map<String, Object> attrs){
		//查询公司
		logger.info("查询公司列表");
		List<FgCompany> companyList = companyServiceImpl.all();
		attrs.put("companyList", companyList);
		
		//查询客户公司
		logger.info("查询客户公司列表");
		List<FgCustomerCompany> customerCompanyList = new ArrayList<FgCustomerCompany>();
		customerCompanyList = fgCustomerCompanyMapper.all();
		attrs.put("customerCompanyList", customerCompanyList);
		
		//查询项目负责人
		logger.info("查询项目负责人列表");
		List<FgStaff> staffList = new ArrayList<FgStaff>();
		staffList = staffServiceImpl.all();
		attrs.put("staffList", staffList);
		
		//查询客户人
		logger.info("查询客户人列表");
		List<FgCustomer> customerList = new ArrayList<FgCustomer>();
		customerList = fgCustomerMapper.all();
		attrs.put("customerList", customerList);
		
		//查询合作商
		logger.info("查询合作商列表");
		List<FgPartnerCompany> partnerCompanyList = new ArrayList<FgPartnerCompany>();
		partnerCompanyList = fgPartnerCompanyMapper.all();
		attrs.put("partnerCompanyList", partnerCompanyList);
		//项目状态
		Map<String, String> projectStatus = new HashMap<String, String>();
		projectStatus = ENUM_PROJECT_STATUS.getProjectStatus();
		attrs.put("projectStatus", projectStatus);
		
		//项目进度
		attrs.put("projectSchedule", ENUM_PROJECT_SCHEDULE.values());
	}
	
	/**
	 * 查询项目信息
	 * @param projectId
	 * @param attrs
	 * @return
	 */
	private Map<String, Object> selectByProjectId(Integer projectId, Map<String, Object> attrs){
		FgProject project = new FgProject();
		List<FgPartnerCompanyDetail> partnerDetailList = new ArrayList<FgPartnerCompanyDetail>();
		List<FgProjectLog> projectLogList = new ArrayList<FgProjectLog>();
		List<FgProjectLog> projectLogList2 = new ArrayList<FgProjectLog>();
		List<FgContractDetail> contractDetailList = new ArrayList<FgContractDetail>();
		
		List<FgContractDetail> contractBillingDetailList = new ArrayList<FgContractDetail>();
		List<FgContractDetail> contractPaymentDetailList = new ArrayList<FgContractDetail>();
		
		FgContract contract = new FgContract();
		if(null != projectId && 0 != projectId){
			project = fgProjectMapper.selectByProjectId(projectId);
			partnerDetailList = fgPartnerCompanyDetailMapper.selectByProjectId(projectId);
			projectLogList = fgProjectLogMapper.selectByProjectId(projectId);
			contract = fgContractMapper.selectByProjectId(projectId);
			contractDetailList = fgContractDetailMapper.selectByProjectId(projectId);
			if(null != contractDetailList ){
				for(FgContractDetail contractDetail:contractDetailList){
					if("BILL".equals(contractDetail.getDetailType())){
						contractBillingDetailList.add(contractDetail);
					}else if("PAY".equals(contractDetail.getDetailType())){
						contractPaymentDetailList.add(contractDetail);
					}
				}
			}
		}else{
			logger.error("没有找到对应的项目数据");
		}
		
		if(projectLogList != null && projectLogList.size() > 0) {
			for(FgProjectLog log : projectLogList) {
				if(log.getTodoSomething() != null && log.getTodoDate() != null && "Y".equals(log.getIsDone())) {
					projectLogList2.add(log);
				}
			}
			projectLogList.removeAll(projectLogList2);
		}
		
		//供应商数据
		List<Map<String, Object>> partnerList = new ArrayList<Map<String, Object>>();
		if(partnerDetailList != null) {
			for(FgPartnerCompanyDetail partner : partnerDetailList) {
				Map<String, Object> map = new HashMap<>();
				map.put("partnerCompanyId", partner.getPartnerCompanyId().toString()); 	//供应商公司ID
				map.put("partnerProductId", partner.getPartnerProductId()); 			//供应商产品/服务ID
				map.put("partnerContactId", partner.getPartnerContactId()); 			//供应商联系人ID
				
				List<FgPartnerProduct> partnerProductList =  partnerProductServiceImpl.selectList(partner.getPartnerCompanyId());
				List<FgPartnerContact> partnerContactList =  partnerContactServiceImpl.selectList(partner.getPartnerCompanyId());

				map.put("partnerProductList", partnerProductList);	//供应商产品/服务下拉框列表
				map.put("partnerContactList", partnerContactList);	//供应商联系人下拉框列表
				
				partnerList.add(map);
			}
		}
		
		//查询客户人
		logger.info("查询客户人列表");
		List<FgCustomer> customerList = new ArrayList<FgCustomer>();
		customerList = fgCustomerMapper.allByCustomerCompanyId(project.getCustomerCompanyId());
		attrs.put("customerList", customerList);
		
		//发票类型
		Map<String, String> billingTypeMap = new HashMap<String, String>();
		billingTypeMap = ENUM_BILLING_TYPE.getBillingType();
		attrs.put("billingTypeMap", billingTypeMap);
		attrs.put("project", project);
		attrs.put("partnerDetailList", partnerDetailList);
		attrs.put("partnerList", partnerList);
		attrs.put("projectLogList", projectLogList);
		attrs.put("projectLogList2", projectLogList2);
		attrs.put("contract", contract);
		attrs.put("contractDetailList", contractDetailList);
		attrs.put("contractBillingDetailList", contractBillingDetailList);
		attrs.put("contractPaymentDetailList", contractPaymentDetailList);
		return attrs;
	}
	
	@RequestMapping("getProjectListByPage")
	@ResponseBody
    public Object getProjectListByPage(FgProject project) throws Exception{
    	//如果传参为空 则取第一页数据
    	String currentPage = null==request.getParameter("currentPage") ? "1" : request.getParameter("currentPage");
    	if("".equals(currentPage)){
    		currentPage = "1";
    	}
    	String pageCount = ProjectConstant.EVERY_PAGE_COUNT;
    	Integer startPage =  (Integer.valueOf(currentPage)-1) * Integer.valueOf(pageCount);
    	project.setPageCount(pageCount);
    	project.setStartPage(startPage.toString());
    	List<String> list = new ArrayList<String>();
    	list.add(ENUM_PROJECT_STATUS.BEFORE.getCode());
    	list.add(ENUM_PROJECT_STATUS.IMPLAMENT.getCode());
    	project.setProjectStatusList(list);
    	List<FgProject> projectList = projectServiceImpl.findFgProjectList(project);
    	if(null == projectList){
    		projectList = new ArrayList<FgProject>();
    	}
    	return projectList;
	}
	
	@RequestMapping("getQueryProjectListByPage")
	@ResponseBody
    public Object getQueryProjectListByPage(FgProject project) throws Exception{
		//获取页数
		List<FgProject> projectList = projectServiceImpl.findFgProjectList(project);
		Integer count = 0;
		if(projectList != null && projectList.size() > 0) {
			count = projectList.size() / 10;
			if(projectList.size() % 10 != 0) {
				count++;
			}
		}
		
    	//如果传参为空 则取第一页数据
    	String currentPage = null == request.getParameter("currentPage") ? "1" : request.getParameter("currentPage");
    	if("".equals(currentPage) || "NaN".equals(currentPage)) {
    		currentPage = "1";
    	}
    	String pageCount = ProjectConstant.EVERY_PAGE_COUNT;
    	Integer startPage =  (Integer.valueOf(currentPage)-1) * Integer.valueOf(pageCount);
    	project.setPageCount(pageCount);
    	project.setStartPage(startPage.toString());
    	List<String> list = new ArrayList<String>();
    	list.add(ENUM_PROJECT_STATUS.BEFORE.getCode());
    	list.add(ENUM_PROJECT_STATUS.IMPLAMENT.getCode());
    	list.add(ENUM_PROJECT_STATUS.REVOKE.getCode());
    	list.add(ENUM_PROJECT_STATUS.FINISH.getCode());
    	project.setProjectStatusList(list);
    	projectList = projectServiceImpl.findFgProjectList(project);
    	
    	Map<String, Object> result = new HashMap<String, Object>();
    	result.put("list", projectList);
    	result.put("count", count);
    	
    	return result;
	}
	
}
